import React from 'react';
import { Card } from 'antd';
import { QueryFilter, ProFormText } from '@ant-design/pro-form';
import { getServiceCode } from './serviceImpl';

import SyntaxHighlighter from 'react-syntax-highlighter';
import { docco } from 'react-syntax-highlighter/dist/esm/styles/hljs';
import { getTableIndex } from '../../service';

import type { TableDetailProps } from './index';

export default (props: TableDetailProps) => {
  // 表名和备注
  const { tableName, tableComment } = props;

  // 如果没有选择表，那么就显示一个提示信息
  if (!tableName) {
    return (
      <div>
        <br />
        请在左侧选中要生成代码的表
      </div>
    );
  }

  // state数据
  const [indexList, setIndexList] = React.useState<Dev.TableIndex[] | undefined>(undefined);
  const [searchValues, setSearchValues] = React.useState<Record<string, any>>({
    nameSpace: 'XXXX',
    subUrl: 'AAAA/BBBB',
  });

  // 查询后台
  React.useEffect(() => {
    const fun = async () => {
      if (tableName) {
        const ren = await getTableIndex(tableName);
        if (ren.data) {
          setIndexList(ren.data);
        }
      } else {
        throw Error(`not find table:${tableName}`);
      }
    };
    fun();
  }, [tableName]);

  /**
   * 保存事件
   * @param values 表单传递过来的参数
   */
  const onFinishHandle = async (values: Record<string, any>) => {
    setSearchValues(values);
  };

  // const indexList = [{ columnCamelName: 'adminId', jsType: 'string', type: 'pk' }];

  return (
    <div>
      <div style={{ marginBottom: 10 }}>
        {tableComment}：{tableName}
      </div>
      <Card>
        <QueryFilter
          onFinish={onFinishHandle}
          submitter={{
            searchConfig: {
              submitText: '生成代码',
            },
          }}
          initialValues={searchValues}
        >
          <ProFormText
            width="md"
            name="nameSpace"
            label="命名空间"
            rules={[
              {
                required: true,
              },
            ]}
          />
          <ProFormText
            width="md"
            name="subUrl"
            label="URL前缀"
            rules={[
              {
                required: true,
              },
            ]}
          />
        </QueryFilter>
      </Card>

      {/* 代码显示区域 */}
      {indexList && (
        <SyntaxHighlighter language="typescript" style={docco}>
          {getServiceCode(
            indexList || [],
            tableName,
            tableComment || '',
            searchValues.nameSpace,
            searchValues.subUrl,
          )}
        </SyntaxHighlighter>
      )}
    </div>
  );
};
